/*
 * Copyright 2002-2006 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package de.riceman.simpleGo.view.views;

import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Iterator;

import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultCaret;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.richclient.application.support.AbstractView;

import de.riceman.simpleGo.SimpleGo;
import de.riceman.simpleGo.events.SimpleGoLifecycleApplicationEvent;
import de.riceman.simpleGo.main.BitMatrix;
import de.riceman.simpleGo.main.GoGame;
import de.riceman.simpleGo.players.Player;

/**
 * This class defines the initial view to be presented in the SimpleGo application. It is
 * constructed automatically by the platform and configured according to the bean
 * specification in the application context.
 * 
 * @author Larry Streepy
 * 
 */
public class ConsoleView extends AbstractView implements ApplicationListener {

	private static final java.lang.String DARK = "X";
	private static final java.lang.String LIGHT = "O";
	private static final java.lang.String EMPTY = " ";
	
	private static final Log logger = LogFactory.getLog(ConsoleView.class);
	
	private GoGame goGame;
	private JScrollPane scrollPane;
	private JTextArea console;
	
    /**
     * Create the actual UI control for this view. It will be placed into the window
     * according to the layout of the page holding this view.
     */
    protected JComponent createControl() {
        // In this view, we're just going to use standard Swing to place a
        // few controls.

    	console = new JTextArea();
    	console.setEditable(false);
    	console.setAutoscrolls(true);
    	console.setFont(new Font("Monospaced", Font.PLAIN, 10));
    	
    	DefaultCaret caret = (DefaultCaret) console.getCaret();
    	caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    	
    	scrollPane = new JScrollPane(console, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);


        JPanel panel = getComponentFactory().createPanel(new BorderLayout());
        panel.add(scrollPane);

        return panel;
    }
	
	/**
	 * Renders the board in ASCII arts.
	 * 
	 * @param dark
	 * @param light
	 * @param dimension
	 * @return the board as String object
	 */
	private String fieldToString(BitMatrix dark, BitMatrix light, int dimension) {
		StringBuffer out = new StringBuffer();
		
		//
		
		for (int i = 0; i < (dimension*dimension); i++) {

			if (i % dimension == 0) {
				out.append("\n");
			}
			
			if (dark.get(0, i)) {
				out.append(DARK + "|");
			} else if (light.get(0, i)) {
				out.append(LIGHT + "|");
			} else {
				out.append(EMPTY + "|");
			}
		}	
		
		return out.toString();
	}
	
	/**
	 * @param move
	 * @return the coordinate as a readable String
	 */
	private String getCoordinate(BitMatrix move) {
		// TODO Auto-generated method stub
		if (move instanceof BitMatrix) {
			int i = move.getIndexOfFirstSetBit();
			int a;
			
			if (i == -1) {
				return "PASSED\n";
			}
			
			a = i / goGame.getConfiguration().getSize();
			i = i % goGame.getConfiguration().getSize();
			
			return "(" + Integer.toString(a) + "/" + Integer.toString(i) + ")\n";
		} else {
			return "";
		}
	}
	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {


		if (event instanceof SimpleGoLifecycleApplicationEvent) {
			
			
			StringBuffer out = new StringBuffer();
			
			SimpleGoLifecycleApplicationEvent lcae = (SimpleGoLifecycleApplicationEvent) event;
			
			if ((lcae.getEventType() == SimpleGoLifecycleApplicationEvent.INITIALIZED) && lcae.objectIs(GoGame.class)) {
				if (logger.isInfoEnabled()) {
					logger.info("ConsoleView received INITIALIZED ApplicationEvent.");
				}
				goGame = (GoGame) lcae.getObject();
				
				out.append(fieldToString(
						goGame.getConfiguration().getDark(),
						goGame.getConfiguration().getLight(),
						goGame.getConfiguration().getSize()));
			}
			
			if (lcae.getEventType() == SimpleGoLifecycleApplicationEvent.MOVE_EXPECTED && lcae.objectIs(Player.class)) {
				
				Player player = (Player) lcae.getObject();
				
				if (logger.isInfoEnabled()) {
					logger.info("ConsoleView received MOVE_EXPECTED ApplicationEvent.");
				}
				out.append("\n__________________________\nMOVE No. " + goGame.getMoveCount() + "\n");
				
				if (player.getPlayer()) {
					out.append("dark player's turn> ");
				} else {
					out.append("light player's turn> ");
				}
			}
			
			if ((lcae.getEventType() == SimpleGoLifecycleApplicationEvent.MOVED && lcae.objectIs(BitMatrix.class)) ||
					(lcae.getEventType() == SimpleGoLifecycleApplicationEvent.PASSED && lcae.objectIs(BitMatrix.class))	) {
				
				BitMatrix move = (BitMatrix) lcae.getObject();
				
				if (logger.isInfoEnabled()) {
					logger.info("ConsoleView received MOVED/PASSED.");
				}
				
				out.append(getCoordinate(move));
				
				out.append(fieldToString(
						goGame.getConfiguration().getDark(),
						goGame.getConfiguration().getLight(),
						goGame.getConfiguration().getSize()));
				
			}
			
			if (lcae.getEventType() == SimpleGoLifecycleApplicationEvent.FINISHED && lcae.objectIs(GoGame.class)) {
		    	goGame = (GoGame) lcae.getObject();
		    	
		    	try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	out.append("PASSED - Game finished.\nRemoving dead groups...");
		    	
		    	//Remove all groups that are not alive.
				goGame.getConfiguration().removeDeadPartitions();
				
				
		    	out.append("\nDark player's result: ");
		    	
		    	out.append(Integer.toString(goGame.getConfiguration().getDarksCaptured()) + " captured enemy stones. ");
		    	
		    	out.append(Integer.toString(goGame.getConfiguration().getValueOfCapturedPartitions(true)) + " captured points.");
		    	
		    	out.append(Integer.toString(goGame.getConfiguration().getLightsDeadStones()) + " dead enemy stones removed.");
		    	
		    	int totalValueOfDark = goGame.getConfiguration().getDarksCaptured() 
		    							+ goGame.getConfiguration().getValueOfCapturedPartitions(true)
		    							+ goGame.getConfiguration().getLightsDeadStones();
		    	
		    	out.append("Total: " + Integer.toString(totalValueOfDark) + "\n");
		    	
		    	out.append("Light player's result: " + Integer.toString(goGame.getConfiguration().getLightsCaptured()) + " captured enemy stones. ");
		    	
		    	out.append(Integer.toString(goGame.getConfiguration().getValueOfCapturedPartitions(false)) + " captured points.");
		    	
		    	out.append(Integer.toString(goGame.getConfiguration().getDarksDeadStones()) + " dead enemy stones removed.");
		    	
		    	int totalValueOfLight = goGame.getConfiguration().getLightsCaptured() 
		    							+ goGame.getConfiguration().getValueOfCapturedPartitions(false)
		    							+ goGame.getConfiguration().getDarksDeadStones();
		    	
		    	out.append("Total: " + Integer.toString(totalValueOfLight) + "\n");
		    	
		    	if (totalValueOfLight > totalValueOfDark) {
		    		out.append("Light wins by " + Integer.toString(totalValueOfLight - totalValueOfDark));
		    	}
		    	if (totalValueOfLight < totalValueOfDark) {
		    		out.append("Dark wins by " + Integer.toString(totalValueOfDark - totalValueOfLight));
		    	}
		    	if (totalValueOfLight == totalValueOfDark) {
		    		out.append("They're both losers ;-D");
		    	}
		    	
		    	out.append(fieldToString(
						goGame.getConfiguration().getDark(),
						goGame.getConfiguration().getLight(),
						goGame.getConfiguration().getSize()));
		    }
			
			if (lcae.getEventType() == SimpleGoLifecycleApplicationEvent.ILLEGALMOVE && lcae.objectIs(GoGame.class)) {
		    	goGame = (GoGame) lcae.getObject();

		    	out.append(" illegal move!\n");
		    }
			
			console.append(out.toString());
		}
		
	}
}
